package coml.zhouxiaoge.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouxiaoge
 * <p>
 * Created by 2022-04-26 23:35
 */
public class DistributeClient {
    private static final String connectString = "192.168.1.11:2181,192.168.1.12:2181,192.168.1.13:2181";
    private static final int sessionTimeout = 2000;
    private final static String parentNode = "/servers";
    private ZooKeeper zooKeeper;

    public void getConnect() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, event -> {
            // 再次启动监听
            try {
                getServerList();
            } catch (InterruptedException | KeeperException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public void getServerList() throws InterruptedException, KeeperException {
        List<String> children = zooKeeper.getChildren(parentNode, true);
        List<String> servers = new ArrayList<>();
        for (String child : children) {
            byte[] data = zooKeeper.getData(parentNode + "/" + child, false, null);
            servers.add(new String(data));
        }
        System.out.println(servers);
    }

    public void business() throws InterruptedException {
        System.out.println("Client is working...");
        Thread.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws Exception {
        DistributeClient distributeClient = new DistributeClient();
        // 1、获取zookeeper连接
        distributeClient.getConnect();
        // 2、获取servers的子节点信息，从中获取服务器列表
        distributeClient.getServerList();
        // 3、业务启动
        distributeClient.business();
    }

}
